package com.example.zhu95.mytimber.entity

import android.text.TextUtils
import com.example.zhu95.mytimber.ConstantValue
import com.example.zhu95.mytimber.ConstantValue.*
import org.litepal.crud.DataSupport

/**
 * @author zhu95
 * @date 2018/3/14 8:15
 */
class PlayQueueRecord : DataSupport() {
    var songids = ""
    var currentId = -1
    var currentPosition = 0

    var playMode = ConstantValue.PLAYMODE_SEQUENCE

    companion object {

        /**
         * 获取播放队列
         */
        fun getPlayqueueSongs(): List<SongBean> {
            val songs = ArrayList<SongBean>();
            songs.clear()
            val songids = getPlayQueueRecord()?.songids
            if (!TextUtils.isEmpty(songids)) {
                // MARK:2018/3/14 java中传入的是正则所以需要转义或者使用[$]
                // //val ids = songids.split("\\$".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                val ids = songids!!.split("$").dropLastWhile { it.isEmpty() }//.toTypedArray()
                for (id in ids) {
                    songs.add(SongData.findSongByID(Integer.parseInt(id)))
                }
            }
            return songs
        }

        /**
         * 获取当前歌曲id
         */
        fun getCurrentSongIdFromDB(): Int {
            val currentId = getPlayQueueRecord()?.currentId
            when (currentId) {
                null -> return -1
                else -> return currentId
            }
        }

        /**
         * 获取当前歌曲播放位置
         */
        fun getCurrentPositionFromDB(): Int {
            val currentPosition = getPlayQueueRecord()?.currentPosition
            when (currentPosition) {
                null -> return 0
                else -> return currentPosition
            }
        }

        /**
         * 获取当前播放模式
         */
        fun getPlayModeFromDB(): Int {
            val playMode = getPlayQueueRecord()?.playMode
            when (playMode) {
                PLAYMODE_SEQUENCE,
                PLAYMODE_SINGLE,
                PLAYMODE_RANDOM
                -> return playMode
                else -> return PLAYMODE_SEQUENCE
            }
        }

        /**
         * 从数据库获取当前播放记录
         */
        private fun getPlayQueueRecord(): PlayQueueRecord? {
            val playQueueRecords = DataSupport.findAll(PlayQueueRecord::class.java)
            if (playQueueRecords != null && playQueueRecords.size > 0) {
                return playQueueRecords[0]
            }
            return null
        }
    }
}
